package com.xique.park.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xique.common.core.constant.UserConstants;
import com.xique.common.core.utils.DateUtils;
import com.xique.common.core.utils.MathUtil;
import com.xique.common.core.utils.SecurityUtils;
import com.xique.common.core.utils.StringUtils;
import com.xique.park.bean.domain.User;
import com.xique.park.bean.dto.ParkUserDTO;
import com.xique.park.bean.request.web.user.SelectParkUserRequest;
import com.xique.park.bean.search.app.ParkUserListSearch;
import com.xique.park.mapper.UserMapper;
import com.xique.park.service.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 门禁用户信息Service业务层处理
 *
 * @author xique
 * @date 2021-12-15
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    /**
     * 查询门禁用户信息
     *
     * @param id 门禁用户信息ID
     * @return 门禁用户信息
     */
    @Override
    public User selectUserById(Long id) {
        return userMapper.selectById(id);
    }

    /**
     * 查询门禁用户信息列表
     *
     * @param user 门禁用户信息
     * @return 门禁用户信息
     */
    @Override
    public List<User> selectUserList(User user) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        if (null != user.getBaseUserId()) {
            wrapper.eq("base_user_id", user.getBaseUserId());
        }
        if (null != user.getParkId()) {
            wrapper.eq("park_id", user.getParkId());
        }
        if (StringUtils.isNotEmpty(user.getUserName())) {
            wrapper.like("user_name", user.getUserName());
        }
        if (StringUtils.isNotEmpty(user.getPhone())) {
            wrapper.like("phone", user.getPhone());
        }
        if (StringUtils.isNotEmpty(user.getAddress())) {
            wrapper.like("address", user.getAddress());
        }
        if (null != user.getId()) {
            wrapper.eq("id", user.getId());
        }
        return userMapper.selectList(wrapper);
    }

    /**
     * 新增门禁用户信息
     *
     * @param user 门禁用户信息
     * @return 结果
     */
    @Override
    public int insertUser(User user) {
        //32位id生成逻辑 = 13位时间戳+19位随机数
        String customId = System.currentTimeMillis() + MathUtil.getRandom(19);
        user.setCustomId(customId);
        user.setCreateTime(DateUtils.getNowDate());
        user.setUpdateTime(DateUtils.getNowDate());
        return userMapper.insert(user);
    }

    /**
     * 修改门禁用户信息
     *
     * @param user 门禁用户信息
     * @return 结果
     */
    @Override
    public int updateUser(User user) {
        user.setUpdateTime(DateUtils.getNowDate());
        return userMapper.updateById(user);
    }

    /**
     * 批量删除门禁用户信息
     *
     * @param ids 需要删除的门禁用户信息ID
     * @return 结果
     */
    @Override
    public int deleteUserByIds(List<Long> ids) {
        return userMapper.deleteBatchIds(ids);
    }

    /**
     * 删除门禁用户信息信息
     *
     * @param id 门禁用户信息ID
     * @return 结果
     */
    @Override
    public int deleteUserById(Long id) {
        return userMapper.deleteById(id);
    }

    @Override
    public List<ParkUserDTO> getParkUserList(ParkUserListSearch search) {
        return userMapper.getParkUserList(search);
    }

    @Override
    public void batchAdd(List<User> userList) {
        long startTime = System.currentTimeMillis();
        SqlSession sqlSession = null;
        try {
            sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            userList.forEach(userMapper::insert);
            sqlSession.commit();
            sqlSession.clearCache();
        } catch (Exception e) {
            log.info("门禁用户信息服务：批量新增异常，异常信息：{}", e.getMessage());
            e.printStackTrace();
            if (sqlSession != null) {
                sqlSession.rollback();
            }
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
        log.info("门禁用户信息服务：批量新增耗时：{}毫秒", System.currentTimeMillis() - startTime);
    }

    @Override
    public List<User> selectUserByPhone(Long parkId, String phone) {
        LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(User::getParkId, parkId);
        queryWrapper.eq(User::getPhone, phone);
        queryWrapper.eq(User::getDelFlag, UserConstants.DelFlag.NORMAL);
        return userMapper.selectList(queryWrapper);
    }

    @Override
    public List<User> selectUserByPhone(String phone) {
        LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(User::getPhone, phone);
        queryWrapper.eq(User::getDelFlag, UserConstants.DelFlag.NORMAL);
        return userMapper.selectList(queryWrapper);
    }

    @Override
    public List<User> selectByIds(List<Long> ids) {
        if (ids.isEmpty()) {
            return null;
        }
        return userMapper.selectBatchIds(ids);
    }

    @Override
    public IPage conditionList(SelectParkUserRequest request) {
        IPage page = new Page(request.getPageNum(), request.getPageSize());
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("park_id", SecurityUtils.getParkId());
        queryWrapper.eq(StringUtils.isNotNull(request.getUserId()),"id",request.getUserId());
        queryWrapper.like(StringUtils.isNotEmpty(request.getUserName()), "user_name", request.getUserName());
        queryWrapper.like(StringUtils.isNotEmpty(request.getAddress()), "address", request.getAddress());
        queryWrapper.like(StringUtils.isNotEmpty(request.getPhone()), "phone", request.getPhone());
        queryWrapper.eq(StringUtils.isNotEmpty(request.getGender()), "gender", request.getGender());
        queryWrapper.eq(StringUtils.isNotEmpty(request.getStatus()), "status", request.getStatus());
        queryWrapper.eq("del_flag", "0");
        queryWrapper.orderByDesc("create_time");
        IPage iPage = userMapper.selectPage(page, queryWrapper);
        return iPage;
    }

}
